package com.example.midicontrol.ui

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View

class PadView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val activePaint = Paint().apply {
        color = 0xFF00FF00.toInt()
        isAntiAlias = true
    }

    private val inactivePaint = Paint().apply {
        color = 0xFF333333.toInt()
        isAntiAlias = true
    }

    var onPadPressed: ((velocity: Int) -> Unit)? = null

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val radius = (width.coerceAtMost(height) / 2 * 0.8f)
        canvas.drawCircle(width/2f, height/2f, radius, inactivePaint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                val velocity = (event.pressure * 127).toInt().coerceIn(1, 127)
                onPadPressed?.invoke(velocity)
                invalidate()
                return true
            }
            MotionEvent.ACTION_UP -> {
                invalidate()
                return true
            }
        }
        return super.onTouchEvent(event)
    }
}
